//一键安排考场
import moment from 'moment'
import {useMainPageStore} from "@/store/mainPageStore";
import pinia from "@/store/store";
import _ from 'lodash';
import {processAppConfig} from "@/util/appConfigUtil";
import {useArrangeStore} from "@/store/arrangeStore";

const appConfig = processAppConfig()
const mainPageStore = useMainPageStore(pinia)
const arrangeStore = useArrangeStore(pinia)

//根据校区分组
const examHallGroupByCampus = _.groupBy(appConfig.examHalls, 'campus')

//快速安排考场
export const fastArrange = () => {

    // appConfig.columnDefines.subjectName.dicMap

    //所有的数据
    var data = mainPageStore.data;


    //先根据学科分组
    let dataGroupBySubject = _.groupBy(data, 'subjectName')

    // {
    //     'a':[]
    // }
    //然后根据校区分组
    for (let dataGroupBySubjectKey in dataGroupBySubject) {
        let item = dataGroupBySubject[dataGroupBySubjectKey];
        dataGroupBySubject[dataGroupBySubjectKey] = _.groupBy(item, 'campus')
    }
    //这个结构
    // {
    //     '00001':{
    //         '1':[],
    //         '2':[]
    //
    //     }
    // }

    for (let dataGroupBySubjectKey in dataGroupBySubject) {
        arrangeBySubject(dataGroupBySubject[dataGroupBySubjectKey])
    }
    //批次好
    //这个结构
    // let a = {
    //     '00001': {
    //         '1':
    //              [
    //{
    //             '0001':[
    //             ],
    //             'dummyHall':[]
    //         }
    //
    //              ]
    //         '2': {
    //             '0001':[],
    //             'dummyHall':[]
    //         },
    //
    //     }
    // }

    var dicMap = appConfig.columnDefines.subjectName.dicMap;

    let subjectList = Object.keys(dataGroupBySubject).map((item => {
        return {
            code: item, name: dicMap.get(item)
        }
    }))
    let arrangeAgg = {}
    for (let dataGroupBySubjectKey in dataGroupBySubject) {
        arrangeAgg[dataGroupBySubjectKey] = {}
        calcTotal(dataGroupBySubject, dataGroupBySubjectKey, arrangeAgg[dataGroupBySubjectKey])
    }

    //更新store
    arrangeStore.$patch({
        arrangeAgg, arrangeData: dataGroupBySubject, subjectList
    })

    console.log(arrangeAgg)
    return dataGroupBySubject;
}


//递归计算 每一层的总和
export const calcTotal = (data, key, obj = {}) => {
    let item = data[key];

    if (item instanceof Array) {
        if (key === 'dummyExamHall') {
            obj.unArrangeNum = item.length;
            obj.arrangeNum = 0;
            obj.total = item.length;
        } else if (key === 'batch') {
            let sum = _.reduce(item, (sum, value) => {
                for (let valueKey in value) {
                    sum += value[valueKey].length;
                }
                return sum;
            }, 0)
            obj.arrangeNum = sum
            obj.unArrangeNum = 0;
            obj.batchNum = item.length;
            obj.total = sum;

        }

    } else if (typeof item === "object") {
        let sum = 0;
        let child = {
            data: null, total: 0, arrangeNum: 0, unArrangeNum: 0
        }
        let unArrangeNum = 0;
        let arrangeNum = 0;
        for (const itemKey in item) {

            child = calcTotal(item, itemKey, obj[itemKey] ? obj[itemKey] : obj[itemKey] = {});
            sum += child.total;
            unArrangeNum += child.unArrangeNum;
            arrangeNum += child.arrangeNum;
        }
        obj.total = sum;
        obj.unArrangeNum = unArrangeNum;
        obj.arrangeNum = arrangeNum;
    }
    return obj;
}


//对每个学科安排考场
export const arrangeBySubject = (subjectData) => {

    for (let campusKey in subjectData) {
        console.log('typeof  campusKey', typeof campusKey, campusKey)
        //当前校区的考场
        let examHallList = examHallGroupByCampus[campusKey];
        if (!examHallList) examHallList = []

        let campusList = subjectData[campusKey]
        let campusListDeepClone = _.cloneDeep(campusList);

        //清空
        campusList = {
            //为分配的
            dummyExamHall: [], //这个是分配的
            batch: []
        }
        // console.log(campusListDeepClone)
        while (campusListDeepClone.length > 0) {
            //同一时间纬度分配考场
            let batchItem = {}

            //如果没有考场 无法分配
            if (examHallList.length === 0) {
                //放到 虚拟考场内
                campusList.dummyExamHall = campusListDeepClone;
                break;
            }
            //填充每一个考场
            //TODO 配置是否进行考试 只选取启用的
            for (let i = 0; i < examHallList.length; i++) {
                let examHall = examHallList[i];
                // if (campusListDeepClone.length <= 0) {
                //     break;
                // }
                //从容量中取 前多少个
                //对examHall层次分组
                batchItem[examHall.code] = _.take(campusListDeepClone, examHall.capacity);
                //然后删除
                campusListDeepClone = _.drop(campusListDeepClone, examHall.capacity)
            }
            // console.log(batchItem)

            //分配完之后 加入一个批次
            campusList.batch.push(batchItem)
        }
        subjectData[campusKey] = campusList
    }

    //打印分配好的数据
    console.log('subjectData', subjectData)

}


//构建未分配的树
export function buildBottomUnArrangeTree(unArrangeList, campus) {
    console.log(appConfig.columnDefines.campus.dicMap.get(campus))
    return [{
        label: `${appConfig.columnDefines.campus.dicMap.get(campus)}(${unArrangeList.length}人)`,
        value: campus,
        children: unArrangeList.map((item) => {
            return {
                label: `${item.studentName}-${item.studentId}`, value: item,
            }
        })
    }]
}

//构建批次树
export function buildLeftBatchTree(batch, campus) {
    console.log(batch, campus)
    let examHallMap = appConfig.examHallMap[campus];
    console.log(appConfig.columnDefines.campus.dicMap.get(campus))


    return [{
        label: `${appConfig.columnDefines.campus.dicMap.get(campus)}(${batch.length}批次)`,
        value: campus,
        children: batch.map((item, key) => {
            let children = []
            let batchExamHallNum = 0;
            let batchTotal = 0;
            let examHallTotal = 0;
            let enough;
            for (let examHallKey in item) {
                batchExamHallNum++;
                let examHallData = item[examHallKey]
                var examHall = examHallMap.get(examHallKey);
                // 这里计算非空的数量
                let examHallDataNum = examHallData.filter(item => item).length
                batchTotal += examHallDataNum;
                examHallTotal += examHall.capacity;
                children.push({
                    label: `${examHall.name}(${examHallDataNum}/${examHall.capacity})`, value: examHallData,
                    disabled: examHallDataNum >= examHall.capacity,
                    capacity: examHall.capacity,
                    num: examHallData.length
                })
            }

            enough = batchTotal >= examHallTotal;
            return {
                label: `第${key + 1}批次(${batchTotal}人|${batchExamHallNum}考场)`, value: item, children,
                enough,
                disabled: enough
            }
        })
    }]

}

//批次数据转换成列表
export function batchConvert2List(batch = [], campus) {
    return _.reduce(batch, (result, batchItem, key) => {

        for (let examHallKey in batchItem) {
            var examHall = appConfig.examHallMap[campus].get(examHallKey);
            console.log(examHall)
            let examStudentList = batchItem[examHallKey];


            if (examHall) {
                result = result.concat(examStudentList.map(item => {
                    item.examHallName = examHall.name;
                    item.examHallKey = examHallKey;
                    item.batchId = key + 1;
                    return item;
                }))
            }
        }
        return result;
    }, [])
}

//构建考试时间
export function buildExamTimeList(timeSetting) {
    let {
        examDates, examTimeSpan, examTimeStep, examTimeRange, excludeTimeRanges
    } = timeSetting;


    let arrangeTimeList = []
    //循环考试日期
    //YYYY-MM-dd
    let index = 0;
    for (const examDate of examDates) {
        //08:00
        let startTime = examTimeRange[0]
        //20:00
        let endTime = examTimeRange[1]

        console.log(examDate + ' ' + endTime + ':00')
        let endDateTime = moment(examDate + ' ' + endTime + ':00');
        console.log(endDateTime.format("YYYY-MM:DD HH:mm"))
        console.log(getMinutes(examTimeStep));
        do {
            let currentStartTime = moment(examDate + ' ' + startTime + ':00');
            let currentEndTime = moment(currentStartTime).add(getMinutes(examTimeStep), "minutes")
            var nextEndTime = moment(currentEndTime).add(getMinutes(examTimeStep), 'minutes').add(getMinutes(examTimeSpan), 'minutes');
            let currentTimeRange = [currentStartTime.format("HH:mm"), currentEndTime.format("HH:mm"),]

            //当前分配的时间范围是否是可信任的时间范围
            var flag = true;
            for (let excludeTimeRange of excludeTimeRanges) {
                //时间冲突 时间区域在配出的范围内
                if (timeRangeIsConflict(currentTimeRange, excludeTimeRange.excludeTimeRange)) {
                    flag = false;
                    break;
                }
            }

            if (flag) {
                arrangeTimeList.push({
                    startTime: currentStartTime.toDate(),
                    startTimeStr: currentStartTime.format("YYYY-MM-DD HH:mm"),
                    endTime: currentEndTime.toDate(),
                    endTimeStr: currentEndTime.format("YYYY-MM-DD HH:mm"),

                })
            }


            startTime = currentEndTime.add(getMinutes(examTimeSpan), 'minutes').format("HH:mm")
            index++;
            //避免设置时间间隔过小导致死循环
            if (index > 500) {
                break;
            }
        } while (nextEndTime <= moment(endDateTime));

    }
    return arrangeTimeList;
}

export function getMinutes(time) {
    let arr = time.split(":")
    return Number(arr[0]) * 60 + Number(arr[1]);
}

//["08:00","09:00"]  ["09:00","11:00"]
export function timeRangeIsConflict(time1, time2) {
    return !(time1[1] <= time2[0] || time2[1] <= time1[0])

}

//移除至未安排的考场
export function moveToDummyExamHall(arrangeData, fromBatchIndex, fromExamHallCode, fromIndex) {
    console.log(fromBatchIndex, fromExamHallCode, fromIndex,)

    let fromExamHallData = arrangeData.batch[fromBatchIndex][fromExamHallCode]

    let temp = fromExamHallData[fromIndex]

    arrangeData.dummyExamHall.push(temp)

    fromExamHallData[fromIndex] = [];


}


//交换考场
export function exchangeExamHall(arrangeData, fromBatchIndex, fromExamHallCode, fromIndex, toExamHallCode, toBatchIndex, toIndex) {
    console.log(arrangeData, fromBatchIndex, fromExamHallCode, fromIndex, toBatchIndex, toExamHallCode)
    //判断toExamHall 是否满人
    console.log(arrangeData.batch)

    let toExamHallData = arrangeData.batch[toBatchIndex - 1][toExamHallCode]
    let fromExamHallData = arrangeData.batch[fromBatchIndex - 1][fromExamHallCode]
    if (!toExamHallData) {
        console.log("考场不存在")
        return {
            code: -1,
            msg: "考场不存在"
        }
    }
    //当前考场的人数
    let examHallNum = toExamHallData.length;

    let examHallConfig = appConfig.examHalls.find(item => item.code === toExamHallCode)
    let examHallCapacity = examHallConfig.capacity

    if (examHallCapacity <= examHallNum) {
        console.log("考场已满")
        return {
            code: -2,
            msg: "考场已满"
        }
    }


    //在无人的区间插入 toIndex=-1 在无人区间插入
    if (toIndex > examHallNum - 1 && toIndex <= examHallCapacity - 1 || toIndex === -1) {
        toExamHallData.push(fromExamHallData[fromIndex])
        //删除哪一个元素
        // fromExamHallData[fromIndex] = null
        _.pullAt(fromExamHallData, fromIndex);

    } else if (toIndex > 0 && toIndex <= examHallNum - 1) {
        //在有人的区间进行交换
        let temp = fromExamHallData[fromIndex]
        fromExamHallData[fromIndex] = toExamHallData[toIndex];
        toExamHallData[toIndex] = temp;
    } else {
        console.log("toBatchIndex 参数有误")
        return {
            code: -3,
            msg: "参数有误"
        }
    }
    return {
        code: 0,
        msg: '调整成功'
    }
}